package com.itheima.controller;

import com.itheima.common.R;
import lombok.Generated;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("上传文件"+file.toString());

        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        
        //通过原始文件名截取后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //利用UUID生成文件名，避免文件名重复造成覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        //该文件目前被存于临时文件目录中，待程序执行完毕后，即被销毁，因此需要将其置于指定文件夹中
        //如果指定的文件目录不存在，需要对其进行创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //返回文件名用于保存
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //通过输出流将文件写回浏览器，在浏览器器中即可显示图片
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] bytes = new byte[1024];
            int length = 0;

            while ((length = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,length);
                outputStream.flush();
            }

            //关闭资源
            fileInputStream.close();
            outputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
